"""
AI功能API路由
"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import desc

from app.database import get_db
from app.models.diary import Diary
from app.models.conversation import Conversation
from app.schemas.ai import ChatRequest, ChatResponse, PersonalInsight, InspirationRequest, InspirationResponse

router = APIRouter()

# 暂时简化用户认证
def get_current_user_id() -> int:
    """获取当前用户ID - 简化版本"""
    return 1


@router.post("/chat", response_model=ChatResponse, summary="AI对话")
async def chat_with_ai(
    request: ChatRequest,
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user_id)
):
    """与AI进行对话，基于个人日记内容"""
    try:
        # 获取用户的相关日记内容
        diaries = db.query(Diary).filter(
            Diary.user_id == current_user_id
        ).order_by(desc(Diary.created_at)).limit(request.context_limit).all()
        
        if not diaries:
            raise HTTPException(status_code=404, detail="暂无日记内容，请先创建日记")
        
        # TODO: 实现RAG功能
        # 1. 将问题转换为向量
        # 2. 在向量数据库中搜索相似内容
        # 3. 构建上下文并调用大模型
        
        # 现在返回模拟响应
        context_diaries = []
        for diary in diaries:
            context_diaries.append({
                "id": diary.id,
                "title": diary.title,
                "content": diary.content[:200] + "..." if len(diary.content) > 200 else diary.content,
                "created_at": diary.created_at.isoformat(),
                "relevance_score": 0.85  # 模拟相关性分数
            })
        
        # 模拟AI回答
        ai_answer = f"根据你的日记记录，我看到你提到了'{request.question}'。从你最近的{len(diaries)}篇日记中，我可以感受到你的思考和成长。这是一个很好的问题，让我来分析一下..."
        
        # 保存对话记录
        conversation = Conversation(
            user_id=current_user_id,
            question=request.question,
            answer=ai_answer,
            related_diaries=[diary.id for diary in diaries],
            tokens_used=150  # 模拟token消耗
        )
        
        db.add(conversation)
        db.commit()
        db.refresh(conversation)
        
        return ChatResponse(
            answer=ai_answer,
            related_diaries=context_diaries,
            tokens_used=150,
            conversation_id=conversation.id
        )
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"AI对话失败: {str(e)}")


@router.get("/insights", response_model=PersonalInsight, summary="获取个人洞察")
async def get_personal_insights(
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user_id)
):
    """获取基于日记内容的个人洞察分析"""
    try:
        # 获取用户所有日记
        diaries = db.query(Diary).filter(Diary.user_id == current_user_id).all()
        
        if not diaries:
            return PersonalInsight()
        
        # 计算统计信息
        total_diaries = len(diaries)
        total_words = sum(diary.word_count for diary in diaries)
        
        # 计算平均情绪
        valid_moods = [diary.mood for diary in diaries if diary.mood is not None]
        average_mood = sum(valid_moods) / len(valid_moods) if valid_moods else None
        
        # 统计最常用标签
        all_tags = []
        for diary in diaries:
            if diary.tags:
                all_tags.extend(diary.tags)
        
        from collections import Counter
        tag_counter = Counter(all_tags)
        most_common_tags = [tag for tag, count in tag_counter.most_common(10)]
        
        # 分析写作频率（按月统计）
        from collections import defaultdict
        monthly_count = defaultdict(int)
        for diary in diaries:
            month_key = diary.created_at.strftime("%Y-%m")
            monthly_count[month_key] += 1
        
        # 情绪趋势（按月）
        monthly_mood = defaultdict(list)
        for diary in diaries:
            if diary.mood is not None:
                month_key = diary.created_at.strftime("%Y-%m")
                monthly_mood[month_key].append(diary.mood)
        
        mood_trend = []
        for month, moods in monthly_mood.items():
            if moods:
                avg_mood = sum(moods) / len(moods)
                mood_trend.append({
                    "month": month,
                    "average_mood": round(avg_mood, 2),
                    "diary_count": len(moods)
                })
        
        mood_trend.sort(key=lambda x: x["month"])
        
        return PersonalInsight(
            total_diaries=total_diaries,
            total_words=total_words,
            average_mood=round(average_mood, 2) if average_mood else None,
            most_common_tags=most_common_tags,
            writing_frequency=dict(monthly_count),
            mood_trend=mood_trend
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取个人洞察失败: {str(e)}")


@router.post("/inspire", response_model=InspirationResponse, summary="获取写作灵感")
async def get_writing_inspiration(
    request: InspirationRequest,
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user_id)
):
    """基于历史日记内容提供写作灵感和建议"""
    try:
        # 获取用户最近的日记
        recent_diaries = db.query(Diary).filter(
            Diary.user_id == current_user_id
        ).order_by(desc(Diary.created_at)).limit(10).all()
        
        if not recent_diaries:
            return InspirationResponse(
                suggestions=["今天发生了什么特别的事情吗？", "你现在的心情如何？", "有什么想要记录的想法吗？"],
                topics=["日常生活", "心情感悟", "工作学习"],
                related_memories=[]
            )
        
        # TODO: 实现基于AI的灵感推荐
        # 1. 分析历史内容的主题和情感
        # 2. 结合当前输入生成个性化建议
        # 3. 推荐相关的历史内容片段
        
        # 现在返回模拟数据
        suggestions = [
            "你可以写写今天的心情变化，以及是什么导致了这种变化",
            "回顾一下最近的一个小目标，你觉得进展如何？",
            "描述一个让你印象深刻的瞬间，无论是开心还是难过的",
            "你最近学到了什么新的东西吗？可以分享一下心得"
        ]
        
        topics = ["情感表达", "目标反思", "生活记录", "学习成长"]
        
        related_memories = []
        for diary in recent_diaries[:3]:
            related_memories.append({
                "id": diary.id,
                "title": diary.title,
                "snippet": diary.content[:100] + "..." if len(diary.content) > 100 else diary.content,
                "created_at": diary.created_at.isoformat(),
                "tags": diary.tags or []
            })
        
        return InspirationResponse(
            suggestions=suggestions,
            topics=topics,
            related_memories=related_memories
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取写作灵感失败: {str(e)}")


@router.get("/conversations", summary="获取对话历史")
async def get_conversation_history(
    skip: int = 0,
    limit: int = 20,
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user_id)
):
    """获取用户的AI对话历史"""
    try:
        conversations = db.query(Conversation).filter(
            Conversation.user_id == current_user_id
        ).order_by(desc(Conversation.created_at)).offset(skip).limit(limit).all()
        
        return [
            {
                "id": conv.id,
                "question": conv.question,
                "answer": conv.answer,
                "created_at": conv.created_at.isoformat(),
                "tokens_used": conv.tokens_used
            }
            for conv in conversations
        ]
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取对话历史失败: {str(e)}")


@router.delete("/conversations/{conversation_id}", summary="删除对话记录")
async def delete_conversation(
    conversation_id: int,
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user_id)
):
    """删除指定的对话记录"""
    try:
        conversation = db.query(Conversation).filter(
            Conversation.id == conversation_id,
            Conversation.user_id == current_user_id
        ).first()
        
        if not conversation:
            raise HTTPException(status_code=404, detail="对话记录不存在")
        
        db.delete(conversation)
        db.commit()
        
        return {"message": "对话记录删除成功"}
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"删除对话记录失败: {str(e)}")